package cn.xy.controller;

import cn.xy.pojo.Books;
import cn.xy.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BooksController {

    @Autowired
    private BooksService booksService;


    /**
     * 查询所有图书
     * @param model
     * @return
     */
    @RequestMapping("/queryAllBook")
    public String queryAllBook(Model model){
        List<Books> booksList = booksService.queryAllBook();
        model.addAttribute("booksList",booksList);
        return "allbook";
    }

    /**
     *  跳转到添加图的页面
     * @return
     */
    @RequestMapping("/toAddBook")
    public String toAddBook(){
        return "addBook";
    }

    /**
     *  添加书籍
     * @param books
     * @return
     */
    @RequestMapping("/addBook")
    public String addBook(Books books){
        booksService.insertBook(books);
        return "redirect:/book/queryAllBook";
    }

    /**
     *  将查询到的数据带入跳转到修改页面 RestFul风格，传的参数id在url后面
     * @param id
     * @return
     */
    @RequestMapping("/toUpdateBook/{id}")
    public String toUpdateBook(@PathVariable int id,Model model){
        model.addAttribute("book", booksService.queryBookById(id));
        return "updateBook";
    }

    /**
     *  修改图书
     * @param books
     * @return
     */
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        booksService.updateBook(books);
        return "redirect:/book/queryAllBook";
    }

    /**
     *  根据id删除图书
     *  RestFul风格，传的参数id在url后面
     * @param id
     * @return
     */
    @RequestMapping("/del/{id}")
    public String deleteBookById(@PathVariable int id){
        booksService.deleteBookById(id);
        return "redirect:/book/queryAllBook";
    }

}
